package com.itmck.config;

import com.alibaba.fastjson.JSONObject;
import com.itmck.component.ApiResultResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ShiroAuthFilter extends FormAuthenticationFilter {

    private SessionManager sessionManager;

    public void setSessionManager(SessionManager sessionManager){
        this.sessionManager = sessionManager;
    }
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        // 删除无效session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        ((DefaultWebSessionManager) this.sessionManager).getSessionDAO().delete(session);

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        try {
            ApiResultResponse<String> restResult = new ApiResultResponse<>();
            restResult.setErrorCode("-406");
            restResult.setMessage("请登录账号");
            writer.print(JSONObject.toJSON(restResult).toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            writer.flush();
            writer.close();
        }
    }
}
